<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Requests\BaseRequest;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Validator;
use App\Http\Response\ResponseEnum;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;


class RedisController extends BaseController
{

    //string字符串
    public function string(Request $request)
    {

        $validate = $request->validate(
            $request->all(),
            [
                "name" => "required"
            ],
            [
                "name.required" => "用户名称必须"
            ]
        );

        return [
            'name' => $validate
        ];
    }

    //list列表
    public function list(Request $request)
    {
        return response()->json(['data' => cache()->get("goods")]);
    }

    //hash哈希
    public function hash(Request $request)
    {
        $v = Validator::make($request->all(), ["name" => "required", "age" => "required"], ["name.required" => "姓名必须"]);


        if ($v->fails()) {

            foreach ($v->errors()->all() as $err) {
                return $this->fail(ResponseEnum::CLIENT_PARAMETER_ERROR, null, $err);
            }

        }

        cache()->flush();
    }

    //set集合
    public function set(Request $request)
    {
        $name = redis()->sPop('lucky');

        return $name;
    }

    //zset有序集合
    public function zset(Request $request)
    {
        $nameList = redis()->zRevRange('rank_24h', 0, 2);

        $data = [];
        foreach ($nameList as $v) {
            $data[$v] = redis()->zScore('rank_24h', $v);
        }

        return $data;
    }

    public function publish(Request $request)
    {
        $uid = $request->get('uid', '');
        $msg = $request->get('msg', '');
        redis()->publish('user/msg/' . $uid, $msg);

        return [
            "data" => "发送成功"
        ];
    }
}
